<!DOCTYPE HTML>
<html>
<head>
  <title>Heater Control</title>
<meta name="viewport" charset="UTF-8" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" />
<link rel="stylesheet" href="css/themes/custom-theme.css" />
<link rel="stylesheet" href="css/jqx.base.css" />
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script src="js/jqxcore.js"></script>
<script src="js/jqxchart.js"></script>
<script src="js/jqxgauge.js"></script>

<style type="text/css">
* {
    -webkit-touch-callout:none;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
}
​</style>

<script type="text/javascript">

$(document).ready(function () {

  $('#linearGauge').jqxLinearGauge({
    orientation: 'vertical',
    width: 100,
    height: 350,
    ticksMajor: { size: '10%', interval: 10 },
    ticksMinor: { size: '5%', interval: 2, style: { 'stroke-width': 1, stroke: '#aaaaaa'} },
    max: 40,
    min: -30,
    pointer: { size: '5%' },
    colorScheme: 'scheme05',
    labels: { interval: 10, formatValue: function (value, position) {
        if (position === 'far') {
            value = (9 / 5) * value + 32;
            if (value === -22) {
                return '°F';
            }
            return value + '°';
        }
        if (value === -30) {
            return '°C';
        }
        return value + '°';
    }},
    ranges: [
    { startValue: -5, endValue: 10, style: { fill: '#FFF157', stroke: '#FFF157'} },
    { startValue: 10, endValue: 25, style: { fill: '#FFA200', stroke: '#FFA200'} },
    { startValue: 25, endValue: 40, style: { fill: '#FF4800', stroke: '#FF4800'}}],
    animationDuration: 1500
  });

  (function worker() {
    $.ajax({
      type: 'POST',
      url: 'mcu.tt', 
      data: {command: 'read_temperature'},
      success: function(textVal) {
        currentVal = Math.round(Number(textVal)*10)/10;
        $('#linearGauge').jqxLinearGauge('value', currentVal);
        $("#currentC").html(currentVal  + " °C");
        $("#currentF").html((Math.round(((9/5)*currentVal+32)*10)/10) + " °F");
      },
      complete: function() {
        setTimeout(worker, 3000);
      }
    });
  })();

  initialize();

  $.post('sys.tt', {command: 'get_power'},
    function(textVal){
      if (textVal.replace(/(\r\n|\n|\r)/gm,"") != 'on')
        $('#power_warn_pop').popup('open');
  });
});

var desiredVal;

// works out the X, Y position of the click inside the canvas from the X, Y position on the page
function getPosition(mouseEvent, sigCanvas) {
   var x, y;
   if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
      x = mouseEvent.pageX;
      y = mouseEvent.pageY;
   } else {
      x = mouseEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      y = mouseEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop;
   }

   return { X: x - sigCanvas.offsetLeft, Y: y - sigCanvas.offsetTop };
}

function initialize() {
   // get references to the canvas element as well as the 2D drawing context
   var sigCanvas = document.getElementById("canvasSignature");
   
   sigCanvas.width  = 316;
   sigCanvas.height = 347;
   sigCanvas.style.width  = '316px';
   sigCanvas.style.height = '347px';

   var context = sigCanvas.getContext("2d");
   context.strokeStyle = 'Black';

   // This will be defined on a TOUCH device such as iPad or Android, etc.
   var is_touch_device = 'ontouchstart' in document.documentElement;

   if (is_touch_device) {
      // create a drawer which tracks touch movements
      var drawer = {
         isDrawing: false,
         touchstart: function (coors) {
            context.beginPath();
            context.moveTo(coors.x, coors.y);
            this.isDrawing = true;
         },
         touchmove: function (coors) {
            if (this.isDrawing) {
               drawLine(0, sigCanvas, context, coors.y);
               //context.lineTo(coors.x, coors.y);
               //context.stroke();
            }
         },
         touchend: function (coors) {
            if (this.isDrawing) {
               this.touchmove(coors);
               this.isDrawing = false;
               $.post("mcu.tt", {command: "set_desired", value: desiredVal});
            }
         }
      };

      // create a function to pass touch events and coordinates to drawer
      function draw(event) {
         event.preventDefault();

         // get the touch coordinates.  Using the first touch in case of multi-touch
         var coors = {
            x: event.targetTouches[0].pageX,
            y: event.targetTouches[0].pageY
         };

         // Now we need to get the offset of the canvas location
         var obj = sigCanvas;

         if (obj.offsetParent) {
            // Every time we find a new object, we add its offsetLeft and offsetTop to curleft and curtop.
            do {
               coors.x -= obj.offsetLeft;
               coors.y -= obj.offsetTop;
            }
  		  // The while loop can be "while (obj = obj.offsetParent)" only, which does return null
  		  // when null is passed back, but that creates a warning in some editors (i.e. VS2010).
            while ((obj = obj.offsetParent) != null);
         }

         // pass the coordinates to the appropriate handler
         drawer[event.type](coors);
      }

      // attach the touchstart, touchmove, touchend event listeners.
      sigCanvas.addEventListener('touchstart', draw, false);
      sigCanvas.addEventListener('touchmove', draw, false);
      //sigCanvas.addEventListener('touchend', draw, false);

      sigCanvas.addEventListener('touchend', function(event) {
        $.post("mcu.tt", {command: "set_desired", value: desiredVal});
      },false);

      // prevent elastic scrolling
      sigCanvas.addEventListener('touchmove', function (event) {
         event.preventDefault();
      }, false);
   }
   else {

      // start drawing when the mousedown event fires, and attach handlers to
      // draw a line to wherever the mouse moves to
      $("#canvasSignature").mousedown(function (mouseEvent) {
         var position = getPosition(mouseEvent, sigCanvas);

         context.moveTo(position.X, position.Y);
         context.beginPath();

         // attach event handlers
         $(this).mousemove(function (mouseEvent) {
            drawLine(mouseEvent, sigCanvas, context);
         }).mouseup(function (mouseEvent) {
            finishDrawing(mouseEvent, sigCanvas, context);
         }).mouseout(function (mouseEvent) {
            finishDrawing(mouseEvent, sigCanvas, context);
         });
      });

   }

   $.post("mcu.tt", {command: "get_desired"}, // init
     function(textVal){
       //sigCanvas.width = sigCanvas.width; // clean
       desiredVal = Number(textVal);
       posY = Math.round((40-desiredVal)*312/70+18);
       context.moveTo(0,posY);
       context.lineTo(316, posY);
       context.stroke();
       $("#desiredText").css({"margin-top": posY - 18});
       $("#desiredC").html(desiredVal  + " °C");
       $("#desiredF").html((Math.round(((9/5)*desiredVal+32)*10)/10) + " °F");
   });
}

// draws a line to the x and y coordinates of the mouse event inside
// the specified element using the specified context
function drawLine(mouseEvent, sigCanvas, context, posY) {

   if(typeof(posY)==='undefined') {
     var position = getPosition(mouseEvent, sigCanvas);
     posY = position.Y;
   }

   sigCanvas.width = sigCanvas.width; // clean
   if (posY < 18) posY = 18;
   //if (posY > 330) posY = 330;
   if (posY > 285) posY = 285.5;
   context.moveTo(0,posY);
   context.lineTo(316, posY);
   context.stroke();
   $("#desiredText").css({"margin-top": posY - 18});
   desiredVal = Math.round((40-(posY-18)*70/312)*10)/10;
   $("#desiredC").html(desiredVal  + " °C");
   $("#desiredF").html((Math.round(((9/5)*desiredVal+32)*10)/10) + " °F");
   //console.info("position = " + posY + ", temp = " + desiredVal);
}

// draws a line from the last coordiantes in the path to the finishing
// coordinates and unbind any event handlers which need to be preceded
// by the mouse down event
function finishDrawing(mouseEvent, sigCanvas, context) {
   // draw the line to the finishing coordinates
   drawLine(mouseEvent, sigCanvas, context);

   context.closePath();

   // unbind any events which could draw
   $(sigCanvas).unbind("mousemove")
               .unbind("mouseup")
               .unbind("mouseout");

   $.post("mcu.tt", {command: "set_desired", value: desiredVal});
}
</script>

</head>

<body>
<div data-role="header" data-position="fixed">
    <span class="ui-title">Heater Control</span>
</div>


<div id="duke" style="margin: 0 auto; margin-top: 10%; width: 96px;">
    <!-- (96 + 110 = 206) + 110 = 316 -->
    <div id="desiredText" style="position: absolute; z-index:0; width: 316px; margin-left: -110px;">
      <span style="float:left;">Desired</span>
      <span id="desiredC" style="float:right;">--.-- °C</span>
      <br>
      <span style="float:left;">Temperature</span>
      <span id="desiredF" style="float:right;">--.-- °F</span>
    </div>
    <div id="linearGauge" style="position: absolute;"></div>
    <canvas id="canvasSignature" style="position: absolute; margin-left: -110px;"></canvas>

    <!-- (96 + 50 = 146) + 50 = 196 -->
    <div style="position: absolute; width: 196px; margin-left: -50px; margin-top: 350px;">
      <span id="currentC" style="float:left;">--.-- °C</span>
      <span id="currentF" style="float:right;">--.-- °F</span>
    </div>
    <div style="position: absolute; width: 96px; margin-left: 18px; margin-top: 350px;">
      Ambient
    </div>
</div>

<div data-role="footer" data-id="foo1" data-position="fixed">
	<div data-role="navbar">
		<ul>
			<li><a href="temperature.html" class="ui-btn-active ui-state-persist">Temperature</a></li>
			<li><a href="humidity.html" rel="external">Humidity</a></li>
			<li><a href="setting.html" rel="external">Setting</a></li>
		</ul>
	</div><!-- /navbar -->
</div><!-- /footer -->


<div data-role="popup" id="power_warn_pop" data-overlay-theme="a" data-theme="c" style="max-width:400px;" class="ui-corner-all">
  <div data-role="header" data-theme="a" class="ui-corner-top">
	<h1>Warning</h1>
  </div>
  <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
	<h3 class="ui-title">Turn on the power?</h3>
	<p>or the heater will not warm up.</p>
	<a href="#" data-role="button" data-inline="true" data-rel="back" data-theme="c">Cancel</a>
	<a href="#" onclick="$.post('sys.tt', {command: 'set_power', value: 'on'});" data-role="button" data-inline="true" data-rel="back" data-transition="flow" data-theme="b">Turn On</a>
  </div>
</div>

</body>
</html>
